import styled from 'styled-components'

import Header from './components/Header'
import Footer from './components/Footer'
import Goods from './components/Goods'
import Counter from './components/Counter'

import { useAppDispatch, useAppSelector } from './hooks'
import { useEffect } from 'react'
import { fetchGoodsList, updateGoodsCount, updateAllState } from './store/reducers/goods'

const Wrapper = styled.div`
  padding: 40px 0 45px 0;
`

export default function App() {
  const dispatch = useAppDispatch()

  const list = useAppSelector((store) => store.goods.list)
  const isFull = useAppSelector((store) => store.goods.list.every((x) => x.goods_state))
  const amount = useAppSelector((store) => store.goods.list.filter((x) => x.goods_state).reduce((t, item) => (t += item.goods_price * item.goods_count), 0))
  const total = useAppSelector((store) => store.goods.list.filter((x) => x.goods_state).reduce((t, item) => (t += item.goods_count), 0))
  useEffect(() => {
    dispatch(fetchGoodsList())
  }, [dispatch])

  return (
    <Wrapper>
      {/* 头部 */}
      <Header />

      {/* 商品列表 */}
      {list.map((item) => (
        <Goods {...item} key={item.id}>
          <Counter count={item.goods_count} onChange={(value) => dispatch(updateGoodsCount({ id: item.id, value }))} />
        </Goods>
      ))}

      {/* 底部 */}
      <Footer isFull={isFull} amount={amount} total={total} onFullChange={(state) => dispatch(updateAllState({ value: state }))} />
    </Wrapper>
  )
}
